package com.zq.config;

import com.zq.utils.TokenUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.credential.HashedCredentialsMatcher;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;


@Slf4j
@Component
public class CustomHashedCredentialsMatcher extends HashedCredentialsMatcher {

    @Autowired
    private RedisTemplate redisTemplate;

    //自定义你的Token校验逻辑，比如与存储在Redis中的Token做对比
    @Override
    public boolean doCredentialsMatch(AuthenticationToken token, AuthenticationInfo info) {
        log.info("doCredentialsMatch");
        String tokenStr = (String) token.getCredentials();
        Integer id = TokenUtil.getUserIdByToken(tokenStr);
        String redisToken = (String)redisTemplate.opsForValue().get("user:token:"+id);
        if(!tokenStr.equals(redisToken))
            throw new AuthenticationException("非法token");
        return true;
    }
}
